package com.xxchat.websocket.netty;

import com.xxchat.entity.dto.TokenUserInfoDTO;
import com.xxchat.redis.RedisComponent;
import com.xxchat.utils.StringTools;
import com.xxchat.websocket.utils.ChannelContextUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@ChannelHandler.Sharable
public class HandlerWebSocket extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger log = LoggerFactory.getLogger(HandlerWebSocket.class);

    @Resource
    private RedisComponent redisComponent;

    @Resource
    private ChannelContextUtils channelContextUtils;

    /**
     * 通道就绪后调用，一般用来做初始化
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("有新的连接加入...");
    }

    /**
     * 连接断开后调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("有连接断开...");
        channelContextUtils.removeContext(ctx.channel());
    }

    /**
     * 读消息
     * @param ctx
     * @param textWebSocketFrame
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        Channel channel = ctx.channel();
        Attribute<String> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        String userId = attribute.get();
        log.info("收到 userId 为 {} 的消息，内容是：{}", userId, textWebSocketFrame.text());
        redisComponent.saveUserHeartBeat(userId);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            WebSocketServerProtocolHandler.HandshakeComplete handshakeComplete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            String uri = handshakeComplete.requestUri();
            String token = getToken(uri);
            if (null == token) {
                log.info("非法请求，已拒绝");
                ctx.channel().close();
                return;
            }
            TokenUserInfoDTO userInfoDTO = redisComponent.getUserInfoByToken(token);
            if (null == userInfoDTO) {
                log.info("非法请求，已拒绝");
                ctx.channel().close();
                return;
            }
            this.channelContextUtils.addContext(userInfoDTO.getUserId(), ctx.channel());
        }
    }

    private String getToken(String uri) {
        if (StringTools.isEmpty(uri) || !uri.contains("?")) {
            return null;
        }
        String[] params = uri.split("\\?");
        if (params.length != 2) {
            return null;
        }
        params = params[1].split("=");
        if (params.length != 2) {
            return null;
        }
        if (!"token".equals(params[0])) {
            return null;
        }
        return params[1];
    }
}
